package com.wmyg.antifake.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.wmyg.antifake.alipay.AlipayConfig;
import com.wmyg.antifake.entity.*;
import com.wmyg.antifake.fabric.FabricDao;
import com.wmyg.antifake.fabric.dto.BatchDto;
import com.wmyg.antifake.repository.*;
import com.wmyg.antifake.service.RecordService;
import com.wmyg.antifake.utils.TsStringCreator;
import com.wmyg.antifake.varaes.sbox.SboxCreator;
import com.wmyg.antifake.wxpay.MiaomarkWxConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 王卓逸
 * @program TODO
 * @description TODO
 * @create 2019-05-08
 */
@Slf4j
@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    RecordRepository recordRepository;

    @Autowired
    ProductRepository productRepository;

    @Autowired
    FactoryRepository factoryRepository;

    @Autowired
    ProductOriginRepository productOriginRepository;

    @Autowired
    BkUserRepository bkUserRepository;

    @Autowired
    FabricDao fabricDao;

    @Autowired
    RedisTemplate redisTemplate;

    @Value(value = "${wxpay.usesandbox}")
    Boolean wxuseSandbox;

    @Value(value = "${alipay.usesandbox}")
    Boolean aliuseSandbox;

    @Value(value = "${qrcode.prefix}")
    String qrcodePrefix;

    private final static Integer DISCOUNT=100;

    private final static Integer UNIT_PRICE=2;

    @Override
    @Transactional(readOnly = false)
    public Integer saveRecord(Record record) {
        Product product = productRepository.getOne(record.getProduct().getProductId());
        if (null == product) {
            return -1;
        } else {
            record.setProduct(product);
        }
        if (null != record.getFactory()) {
            Factory factory = factoryRepository.getOne(record.getFactory().getFactoryId());
            if (null == factory) {
                return -1;
            } else {
                record.setFactory(factory);
            }
        } else if(null != record.getOrigin()) {
            ProductOrigin origin = productOriginRepository.getOne(record.getOrigin().getOriginId());
            if (null == origin) {
                return -1;
            } else {
                record.setOrigin(origin);
            }
        }
//        else {
//            return -1;
//        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date zero = calendar.getTime();
        String batch = TsStringCreator.randomString(2);
        while (recordRepository.countByProductAndBatchAndCreateTimeAfter(record.getProduct(), batch, zero) > 0) {
            batch = TsStringCreator.randomString(2);
        }
        record.setBatch(batch);
        record.setUnitPrice(UNIT_PRICE);
        record.setTotalPrice(record.getTotal() * UNIT_PRICE);
        record.setDiscount(DISCOUNT);
        record.setFinalPrice(DISCOUNT * record.getTotalPrice() / 100);
        recordRepository.save(record);
        return record.getRecordId();
    }

    @Override
    @Async("asyncCreateCode")
    public void produceCode(Integer recordId) {
        String rediskey = "RecordProgress" + recordId;
        Record record = recordRepository.findByRecordId(recordId);
        redisTemplate.opsForValue().set(rediskey, 0);
        SimpleDateFormat format = new SimpleDateFormat("yyMMdd");
        String dateCode = format.format(record.getCreateTime());
        int[] key = new int[10];
        for (int i=0; i<key.length; i++) {
            Random random = new Random();
            key[i] = random.nextInt(10);
            log.info("key[{}] is {}", i, key[i]);
        }
        BatchDto batchDto = new BatchDto("(01)0" + record.getProduct().getProductId()
                + "(10)" + dateCode + "(21)" + record.getBatch(),
                record.getEnterCase(), record.getEnterBox(), record.getEnterPack(),
                null == record.getFactory() ? 0 : record.getFactory().getFactoryId(),
                null == record.getOrigin() ? 0 : record.getOrigin().getOriginId(), key);
        fabricDao.invoke("SaveQRs", batchDto);
        redisTemplate.opsForValue().set(rediskey, 10);
        String excelName = record.getProduct().getProductId() + "-" + record.getBatch() + dateCode;
        String excelFile = "/mnt/files/excel/" + excelName;
//        SXSSFWorkbook wb = new SXSSFWorkbook(100);
//        Sheet sheet = null;
//        Row row = null;
//        Cell cell = null;
//        sheet = wb.createSheet();
        Integer progress = 0;
//        Integer rowNo = 0;
        File file = new File(excelFile);
        FileOutputStream writer = null;
        BufferedWriter fileWriter = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            writer = new FileOutputStream(file, true);
            fileWriter = new BufferedWriter(new OutputStreamWriter(writer, StandardCharsets.UTF_8), 1024 * 1024);
            if (record.getEnterCase() != 0) {
                for (int i = 0; i < record.getEnterCase(); i++) {


                    //  int cases=record.getEnterCase();
                    int boxes=record.getEnterBox();
                    int packs=record.getEnterPack();


                    String caseCode = "(01)0" + record.getProduct().getProductId()
                            + "(10)" + dateCode + "(21)" + record.getBatch() + "X"
                            + SboxCreator.encrypt(TsStringCreator.parseInt(0, 5)
                            + TsStringCreator.parseInt(i + 1, 5)
                            + TsStringCreator.parseInt(boxes, 5), key);



//            fileWriter.write(caseCode + "\n");
//            fileWriter.flush();




                    if (packs  == 0  && boxes==0 ) {  // one case column

                        progress++;
                        redisTemplate.opsForValue().set(rediskey, progress * 80 / record.getTotal() + 10);
                        fileWriter.write(qrcodePrefix + caseCode + "\r\n");

                    }
                    else if (boxes != 0 &&  packs==0) {  // col: case | box

                        fileWriter.write(qrcodePrefix + caseCode + "\t");
                        for (int j = 0; j < boxes; j++) {
                            String boxCode = "(01)0" + record.getProduct().getProductId()
                                    + "(10)" + dateCode + "(21)" + record.getBatch() + "H"
                                    + SboxCreator.encrypt(TsStringCreator.parseInt(i + 1, 5)
                                    + TsStringCreator.parseInt(j + 1, 5)
                                    + TsStringCreator.parseInt(record.getEnterPack(), 5), key);
                            //log.info(boxCode);

                            progress++;
                            redisTemplate.opsForValue().set(rediskey, progress * 80 / record.getTotal() + 10);

                            if (j == boxes - 1) {
                                fileWriter.write(qrcodePrefix + boxCode);
                            } else {
                                fileWriter.write(qrcodePrefix + boxCode + "\t");
                            }
//
//                        if (record.getEnterPack() != 0) {
////                            row = sheet.createRow(rowNo);
////                            cell = row.createCell(0);
////                            cell.setCellValue(qrcodePrefix + caseCode);
////                            cell = row.createCell(1);
////                            cell.setCellValue(qrcodePrefix + boxCode);
//                            fileWriter.write(qrcodePrefix + caseCode + "\t");
//                            fileWriter.write(qrcodePrefix + boxCode + "\t");
//
////                fileWriter.write(boxCode + "\n");
////                fileWriter.flush();
//                            for (int k = 0; k < record.getEnterPack(); k++) {
//                                String packCode = "(01)0" + record.getProduct().getProductId()
//                                        + "(10)" + dateCode + "(21)" + record.getBatch() + "D"
//                                        + SboxCreator.encrypt(TsStringCreator.parseInt(i + 1, 5)
//                                        + TsStringCreator.parseInt(j + 1, 5)
//                                        + TsStringCreator.parseInt(k + 1, 5), key);
//                                log.info(packCode);
//
////                                cell = row.createCell(k + 2);
////                                cell.setCellValue(qrcodePrefix + packCode);
//                                fileWriter.write(qrcodePrefix + packCode + "\t");
//                                progress++;
//                                redisTemplate.opsForValue().set(rediskey, progress * 80 / record.getTotal() + 10);
////                    fileWriter.write(packCode + "\n");
//                            }
////                            rowNo++;
//                            fileWriter.write("\n");
//                        } else {
////                            cell = row.createCell(j + 1);
////                            cell.setCellValue(qrcodePrefix + boxCode);
//                            fileWriter.write(qrcodePrefix + boxCode + "\t");
//                        }
                        }
                        fileWriter.write("\r\n");
                    }
                    else if (boxes == 0 &&  packs !=0) {  // col: case | packs   abandon
                        fileWriter.write(qrcodePrefix + caseCode + "\t");
                        for (int j = 0; j < packs; j++) {
                            String boxCode = "(01)0" + record.getProduct().getProductId()
                                    + "(10)" + dateCode + "(21)" + record.getBatch() + "D"
                                    + SboxCreator.encrypt(TsStringCreator.parseInt(i + 1, 5)
                                    + TsStringCreator.parseInt(boxes, 5)
                                    + TsStringCreator.parseInt(j++, 5), key);
                            //log.info(boxCode);

                            progress++;
                            redisTemplate.opsForValue().set(rediskey, progress * 80 / record.getTotal() + 10);

                            if (j == packs - 1) {
                                fileWriter.write(qrcodePrefix + boxCode);
                            } else {
                                fileWriter.write(qrcodePrefix + boxCode + "\t");
                            }

                        }
                        fileWriter.write("\r\n");

                    } else {  //clos : case | box | pack

                        for (int j = 0; j < boxes; j++) {

                            fileWriter.write(qrcodePrefix + caseCode + "\t");

                            String boxCode = "(01)0" + record.getProduct().getProductId()
                                    + "(10)" + dateCode + "(21)" + record.getBatch() + "H"
                                    + SboxCreator.encrypt(TsStringCreator.parseInt(i + 1, 5)
                                    + TsStringCreator.parseInt(j + 1, 5)
                                    + TsStringCreator.parseInt(record.getEnterPack(), 5), key);

                            progress++;
                            redisTemplate.opsForValue().set(rediskey, progress * 80 / record.getTotal() + 10);

                            fileWriter.write(qrcodePrefix + boxCode + "\t");
                            for (int q = 0; q< packs; q++) {
                                String packCode = "(01)0" + record.getProduct().getProductId()
                                        + "(10)" + dateCode + "(21)" + record.getBatch() + "D"
                                        + SboxCreator.encrypt(TsStringCreator.parseInt(i + 1, 5)
                                        + TsStringCreator.parseInt(j + 1, 5)
                                        + TsStringCreator.parseInt(q+1, 5), key);
                                //log.info(boxCode);

                                progress++;
                                redisTemplate.opsForValue().set(rediskey, progress * 80 / record.getTotal() + 10);

                                if (j == packs - 1) {
                                    fileWriter.write(qrcodePrefix + packCode);
                                } else {
                                    fileWriter.write(qrcodePrefix + packCode + "\t");
                                }

                            }
//

                            fileWriter.write("\r\n");
                        }



                    }

                }
            } else if (record.getEnterBox() != 0) {  //two cols

                if(record.getEnterPack()  ==0) {   // one cols
                    for (int i = 0; i < record.getEnterBox(); i ++) {
                        String boxCode = "(01)0" + record.getProduct().getProductId()
                                + "(10)" + dateCode + "(21)" + record.getBatch() + "H"
                                + SboxCreator.encrypt(TsStringCreator.parseInt(0, 5)
                                + TsStringCreator.parseInt(i + 1, 5)
                                + TsStringCreator.parseInt(record.getEnterPack(), 5), key);
                        progress++;
                        redisTemplate.opsForValue().set(rediskey, progress * 80 / record.getTotal() + 10);
                        fileWriter.write(qrcodePrefix + boxCode + "\r\n");
                    }
                } else{

                    for (int i = 0; i < record.getEnterBox(); i ++) {
                        String boxCode = "(01)0" + record.getProduct().getProductId()
                                + "(10)" + dateCode + "(21)" + record.getBatch() + "H"
                                + SboxCreator.encrypt(TsStringCreator.parseInt(0, 5)
                                + TsStringCreator.parseInt(i + 1, 5)
                                + TsStringCreator.parseInt(record.getEnterPack(), 5), key);
                        log.info(boxCode);

                        //  progress++;
                        redisTemplate.opsForValue().set(rediskey, progress * 80 / record.getTotal() + 10);

//                row = sheet.createRow(i);
//                cell = row.createCell(0);
//                cell.setCellValue(qrcodePrefix + boxCode);


                        fileWriter.write(qrcodePrefix + boxCode + "\t");
                        int packs=record.getEnterPack();
                        for (int j = 0; j < packs; j ++) {
                            String packCode = "(01)0" + record.getProduct().getProductId()
                                    + "(10)" + dateCode + "(21)" + record.getBatch() + "D"
                                    + SboxCreator.encrypt(TsStringCreator.parseInt(0, 5)
                                    + TsStringCreator.parseInt(i + 1, 5)
                                    + TsStringCreator.parseInt(j + 1, 5), key);
                            log.info(packCode);

                            progress++;
                            redisTemplate.opsForValue().set(rediskey, progress * 80 / record.getTotal() + 10);

//                    cell = row.createCell(j + 1);
////                    cell.setCellValue(qrcodePrefix + packCode);
                            if(j == packs -1) {
                                fileWriter.write(qrcodePrefix + packCode);
                            }
                            else{
                                fileWriter.write(qrcodePrefix + packCode + "\t");
                            }

                        }
                        fileWriter.write("\r\n");
                    }

                }


            } else {  //  one cols
                for (int i = 0; i < record.getEnterPack(); i ++) {
                    String packCode = "(01)0" + record.getProduct().getProductId()
                            + "(10)" + dateCode + "(21)" + record.getBatch() + "D"
                            + SboxCreator.encrypt(TsStringCreator.parseInt(0, 5)
                            + TsStringCreator.parseInt(0, 5)
                            + TsStringCreator.parseInt(i + 1, 5), key);
                    log.info(packCode);

                    // progress++;
                    redisTemplate.opsForValue().set(rediskey, progress * 80 / record.getTotal() + 10);

//                row = sheet.createRow(i);
//                cell = row.createCell(0);
//                cell.setCellValue(qrcodePrefix + packCode);
                    fileWriter.write(qrcodePrefix + packCode + "\r\n");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
//            File file = new File(excelFile);
//            if (!file.exists()) {
//                file.createNewFile();
//            }
//            FileOutputStream fOut = new FileOutputStream(excelFile);
//            wb.write(fOut);
//            fOut.flush();
//            fOut.close();
                fileWriter.flush();
                writer.flush();
                fileWriter.close();
                writer.close();
                record.setPayState(5);
                record.setExcelName(excelName);
                recordRepository.save(record);
                redisTemplate.opsForValue().set(rediskey, 100);
            } catch (Exception e) {
                record.setPayState(6);
                recordRepository.save(record);
                log.error("The write excel failed because {}", e);
            }
        }
    }

    @Override
    public Record getRecord(Integer recordId) {
        return recordRepository.findByRecordId(recordId);
    }

    @Override
    public String wxPayPre(Integer recordId, String clientIp) {
        Record record = recordRepository.findByRecordId(recordId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSS");
        try {
            Date now = new Date();
            if (StringUtils.isNotBlank(record.getWxpayCodeUrl())) {
                Date old = sdf.parse(record.getWxpayId().substring(0, 15));
                if (now.getTime() - old.getTime() < 1000 * 60 * 60 * 2) {
                    return record.getWxpayCodeUrl();
                }
            }
            String outTradeNo = sdf.format(now) + TsStringCreator.parseInt(record.getRecordId(), 17);
            MiaomarkWxConfig miaomarkWxConfig = new MiaomarkWxConfig();
            WXPay wxpay = new WXPay(miaomarkWxConfig, WXPayConstants.SignType.MD5, wxuseSandbox);
            if (wxuseSandbox) {
                miaomarkWxConfig.retrieveSandboxSignKey(wxpay);
            }
            Map<String, String> data = new HashMap<String, String>();
            data.put("body", "妙码服务生成二维码" + record.getTotal() + "个");
            data.put("out_trade_no", outTradeNo);
            data.put("device_info", "");
            data.put("fee_type", "CNY");
            if (wxuseSandbox) {
                data.put("total_fee", "301");
            } else {
                data.put("total_fee", record.getFinalPrice().toString());
            }
            data.put("spbill_create_ip", clientIp);
            if (wxuseSandbox) {
                data.put("notify_url", "https://apid.miaomark.cn/notice/wxpay");
            } else {
                data.put("notify_url", "https://api.miaomark.cn/notice/wxpay");
            }
            data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
            data.put("product_id", outTradeNo);
            data.put("attach", "CREATECODE");
            Map<String, String> resp = wxpay.unifiedOrder(data);
            if (WXPayConstants.SUCCESS.equals(resp.get("return_code")) &&
                WXPayConstants.SUCCESS.equals(resp.get("result_code"))) {
                String code = resp.get("code_url");
                record.setWxpayCodeUrl(code);
                record.setWxpayId(outTradeNo);
                record.setWxpayPrepayId(resp.get("prepay_id"));
                record.setPayState((record.getPayState() | 1) & 3);
                recordRepository.save(record);
                return code;
            } else {
                log.error("The wxpay has a error with {}", resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    @Override
    public String aliPayPre(Integer recordId) {
        Record record = recordRepository.findByRecordId(recordId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSS");
        try {

            Date now = new Date();
            if (StringUtils.isNotBlank(record.getAlipayCodeUrl())) {
                Date old = sdf.parse(record.getAlipayId().substring(1, 16));
                if (now.getTime() - old.getTime() < 1000 * 60 * 60 * 2) {
                    return record.getAlipayCodeUrl();
                }
            }
            String outTradeNo = "C" + sdf.format(now) + TsStringCreator.parseInt(record.getRecordId(), 16);
            AlipayClient alipayClient = null;
            if (aliuseSandbox) {
                alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
            } else {
                alipayClient = new DefaultAlipayClient(AlipayConfig.URL_PROD, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY_PROD, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY_PROD, AlipayConfig.SIGNTYPE);
            }
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
            AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
            model.setOutTradeNo(outTradeNo);
            model.setSubject("妙码服务生成二维码" + record.getTotal() + "个");
            model.setTotalAmount(record.getFinalPrice() / 100 + "." + record.getFinalPrice() % 100);
            model.setTimeoutExpress("2h");
            request.setBizModel(model);
            request.setNotifyUrl(AlipayConfig.notify_url);
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            log.info("recieve ali response {}", response);
            if (response.isSuccess()) {
                String code = response.getQrCode();
                record.setAlipayCodeUrl(code);
                record.setAlipayId(outTradeNo);
                record.setPayState((record.getPayState() | 2) & 3);
                recordRepository.save(record);
                return code;
            } else {
                log.error("The alipay has a error with {}", response.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    @Override
    public void download(String excelName, String username) {
        Record record = recordRepository.findByExcelName(excelName);
        DownloadInfo downloadInfo = new DownloadInfo();
        downloadInfo.setOperator(username);
        record.getDownloadInfos().add(downloadInfo);
        recordRepository.save(record);
    }

    @Override
    public Page<Record> getRecordPage(String username, Integer index, String somethingLike, Date startTime, Date endTime, Integer state) {
        String s = "%" + somethingLike + "%";
        BkUser user = bkUserRepository.findByUsername(username);
        if (null != user && null != user.getCompany()) {
            List<Product> products = null;
            if (StringUtils.isBlank(somethingLike)) {
                products = productRepository.findByCompanyOrderByCreateTimeDesc(user.getCompany());
            } else {
                products = productRepository.findByProductIdLikeOrProductNameLikeAndCompanyOrderByCreateTimeDesc(s, s, user.getCompany());
            }
            if (null == state) {
                if (null == startTime && null == endTime) {
                    return recordRepository.findByProductIsInOrderByCreateTimeDesc(products, PageRequest.of(index, 10));
                } else if (null == startTime) {
                    return recordRepository.findByProductIsInAndCreateTimeBeforeOrderByCreateTimeDesc(products, endTime, PageRequest.of(index, 10));
                } else if (null == endTime) {
                    return recordRepository.findByProductIsInAndCreateTimeBetweenOrderByCreateTimeDesc(products, startTime, new Date(), PageRequest.of(index, 10));
                } else {
                    return recordRepository.findByProductIsInAndCreateTimeBetweenOrderByCreateTimeDesc(products, startTime, endTime, PageRequest.of(index, 10));
                }
            } else if (state < 4) {
                if (null == startTime && null == endTime) {
                    return recordRepository.findByProductIsInAndPayStateLessThanOrderByCreateTimeDesc(products, state, PageRequest.of(index, 10));
                } else if (null == startTime) {
                    return recordRepository.findByProductIsInAndPayStateLessThanAndCreateTimeBeforeOrderByCreateTimeDesc(products, state, endTime, PageRequest.of(index, 10));
                } else if (null == endTime) {
                    return recordRepository.findByProductIsInAndPayStateLessThanAndCreateTimeBetweenOrderByCreateTimeDesc(products, state, startTime, new Date(), PageRequest.of(index, 10));
                } else {
                    return recordRepository.findByProductIsInAndPayStateLessThanAndCreateTimeBetweenOrderByCreateTimeDesc(products, state, startTime, endTime, PageRequest.of(index, 10));
                }
            } else {
                if (null == startTime && null == endTime) {
                    return recordRepository.findByProductIsInAndPayStateOrderByCreateTimeDesc(products, state, PageRequest.of(index, 10));
                } else if (null == startTime) {
                    return recordRepository.findByProductIsInAndPayStateAndCreateTimeBeforeOrderByCreateTimeDesc(products, state, endTime, PageRequest.of(index, 10));
                } else if (null == endTime) {
                    return recordRepository.findByProductIsInAndPayStateAndCreateTimeBetweenOrderByCreateTimeDesc(products, state, startTime, new Date(), PageRequest.of(index, 10));
                } else {
                    return recordRepository.findByProductIsInAndPayStateAndCreateTimeBetweenOrderByCreateTimeDesc(products, state, startTime, endTime, PageRequest.of(index, 10));
                }
            }
        }
        return null;
    }

    @Override
    public void cancelRecord(Integer recordId) {
        Record record = recordRepository.findByRecordId(recordId);
        record.setPayState(8);
        recordRepository.save(record);
    }
}
